package GuessNumber;

import static java.lang.Thread.currentThread;

/**
 * @Author mao
 * @Date 2025/11/18
 * @Description 数字猜测线程
 */
class NumberGuesser implements Runnable {
    private final NumberSync numberSync;

    public NumberGuesser(NumberSync numberSync) {
        this.numberSync = numberSync;
    }

    @Override
    public void run() {
        int targetNumber = numberSync.getTargetNumber();
        int low = 1;
        int high = 100;
        int guess = -1;

        while (guess != targetNumber && !numberSync.isGameCompleted()) {
            // 使用二分法查找
            guess = low + (high - low) / 2;
            numberSync.incrementGuessCount();

            System.out.print(currentThread().getName()+"@ ");
            System.out.println("第 " + numberSync.getGuessCount() + " 次猜测: " + guess);

            System.out.print(currentThread().getName()+"@ ");
            if (guess == targetNumber) {
                System.out.println("猜测答案是: " + guess + " 发现自己猜对了！");
                numberSync.setGameCompleted(true);
            } else if (guess < targetNumber) {
                System.out.println("发现小了 调整范围: " + (guess + 1) + " - " + high);
                low = guess + 1;
            } else {
                System.out.println("发现大了 调整范围: " + low + " - " + (guess - 1));
                high = guess - 1;
            }

//            // 短暂延迟以便观察
//            try {
//                Thread.sleep(100);
//            } catch (InterruptedException e) {
//                Thread.currentThread().interrupt();
//                break;
//            }
        }
    }
}
